package net.fdukedom.epicurus.presentation.filters;

import net.fdukedom.epicurus.presentation.SessionData;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Checks that user is logged in.
 *
 * @author Dmitry Y. Kochelaev
 */
public class CheckRoleFilter extends AbstractHttpFilter {

    /**
     * Public area url prefixes.
     */
    private String userArea;

    /**
     * Login page url.
     */
    private RequestDispatcher loginPage;

    @Override
    public void init(FilterConfig config) {
        super.init(config);

        ServletContext application = config.getServletContext();

        userArea = config.getInitParameter("userArea");
        loginPage = application.getRequestDispatcher(config.getInitParameter("loginPage"));
    }

    protected void doFilter(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws IOException, ServletException{
        boolean loggedIn = true;
        String path = request.getServletPath();
        if (SessionData.getInstance(request).getUser() == null) {
            loggedIn = false;
        }
        request.setAttribute("isLoggedIn", loggedIn);
        if (path.startsWith(userArea) && !loggedIn) {
            loginPage.forward(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
